package com.paper.tiger.easy.rpc.s.client.client;

import com.paper.tiger.easy.rpc.s.client.common.Dove;
import com.paper.tiger.easy.rpc.s.client.common.LetterType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/6/16 15:01
 * @since JDK 1.8
 */
public class DoveClientHeartBeatHandler extends ChannelInboundHandlerAdapter
{

    private static Logger logger = LoggerFactory.getLogger(DoveClientHeartBeatHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        Dove dove = (Dove) msg;
        if (dove.getLetterType() == LetterType.HEART_BEAT_RESP.getCode()){
            ReferenceCountUtil.release(msg);
        }else {
            ctx.fireChannelRead(msg);
        }
    }

    /**
     * 客户端连接成功
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {

        logger.info("channel-active");
        // 执行定时任务，每隔5秒发送服务器心跳包

        Dove dove = new Dove();
        dove.setLetterType(LetterType.HEART_BEAT.getCode());

        // 每隔5秒，向服务器发送一次心跳包
        ctx.executor().scheduleAtFixedRate(() ->
        {
            ctx.channel().writeAndFlush(dove);

        }, 0, 5, TimeUnit.SECONDS);
        // 触发下一个
        ctx.fireChannelActive();

    }

    /**
     * 客户端取消注册
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception
    {
        ContextManager.getInstance().removeClientChannel(ctx.channel());
    }
}
